import jwt
from rest_framework_jwt.compat import get_username_field, get_username
from datetime import datetime

from rest_framework_jwt.settings import api_settings
from rest_framework_jwt.utils import jwt_get_secret_key


def jwt_response_payload_error_handler(serializer, request=None):
    print(serializer.errors)
    return {
        'message': serializer.errors.get("non_field_errors")[0]
    }


def jwt_response_payload_handler(token, user=None, request=None):
    return {
        'tokenInfo': {**token, 'user_id': user.id},
        'message': 'OK'
    }


def jwt_refresh_payload_handler(user):
    username_field = get_username_field()
    username = get_username(user)

    payload = {'user_id': user.pk, 'username': username,
               'exp': datetime.utcnow() + api_settings.JWT_REFRESH_EXPIRATION_DELTA, username_field: username}
    return payload


def jwt_refresh_decode_handler(token):
    options = {
        'verify_exp': api_settings.JWT_REFRESH_EXPIRATION_DELTA,
    }
    # get user from token, BEFORE verification, to get user secret key
    unverified_payload = jwt.decode(token, None, False)
    secret_key = jwt_get_secret_key(unverified_payload)
    return jwt.decode(
        token,
        api_settings.JWT_PUBLIC_KEY or secret_key,
        api_settings.JWT_VERIFY,
        options=options,
        leeway=api_settings.JWT_LEEWAY,
        audience=api_settings.JWT_AUDIENCE,
        issuer=api_settings.JWT_ISSUER,
        algorithms=[api_settings.JWT_ALGORITHM]
    )
